package com.lzy.wzy.utils;

import com.lzy.wzy.model.FoxMailMessage;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;


@Component
public class EmailUtils {

    private static final Properties prop = new Properties();

    static {
        prop.put("mail.transport.protocol", "smtp"); // 指定协议

        prop.put("mail.smtp.host", "10.8.0.5"); // 主机

        prop.put("mail.smtp.port", 25); // 端口

        prop.put("mail.smtp.auth", "true"); // 用户密码认证

        prop.put("mail.debug", "true"); // 调试模式
    }

    public void sendEmail(FoxMailMessage msg) throws MessagingException {
        Session session = Session.getDefaultInstance(prop);

        MimeMessage message = new MimeMessage(session);

        message.setSubject(msg.getSubject());

        message.setSentDate(new Date());

        message.setSender(new InternetAddress("zy.wang@timevary.com"));

        message.setRecipients(Message.RecipientType.TO, msg.getAddresses());


        Multipart multipart=new MimeMultipart();

        BodyPart bodyPart=new MimeBodyPart();

        bodyPart.setContent(msg.getContent(), "text/html; charset=utf-8");

      //  message.setText(msg.getContent()); // 简单纯文本邮件

        multipart.addBodyPart(bodyPart);

        message.saveChanges(); // 保存邮件(可选)


        Transport trans = session.getTransport();

        trans.connect("zy.wang@timevary.com", "wzy2020");

        trans.sendMessage(message, message.getAllRecipients());

        trans.close();

    }
}
